<?php
namespace common\modules\modularity\backend\controllers;

use common\modules\modularity\models\Modularity;
use yii\web\Controller;
use yii\data\ArrayDataProvider;

class DefaultController extends Controller
{

    public $modularityService;

    public function init()
    {
        parent::init();
        $this->modularityService = getModularityService();
    }

    public function actionIndex()
    {
        $modules = $this->modularityService->getAllModules();
        $dataProvider = new ArrayDataProvider([
            'allModels' => $modules,
              'sort' => [
                'attributes' => ['id'],
              ]
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

    public function actionInstall($id)
    {
        if (!Modularity::findOne(['id' => $id]))
        {
            $model = new Modularity();
            $model->id = $id;
            $model->enable_backend = 0;
            $model->enable_frontend = 0;
            $model->enable_api = 0;
            $model->save();
        }

        $modules = $this->modularityService->getAllModules();
        if (isset($modules[$id]) && $modules[$id]['instance'] !== null) {
            $modules[$id]['instance']->install();
        }
        return $this->redirect([
            'index'
        ]);
    }

    public function actionUninstall($id)
    {
        Modularity::deleteAll([
            'id' => $id
        ]);

        $modules = $this->modularityService->getAllModules();
        if (isset($modules[$id]) && $modules[$id]['instance'] !== null) {
            $modules[$id]['instance']->uninstall();
        }

        return $this->redirect([
            'index'
        ]);
    }

    public function actionActive($id, $app)
    {
        $field = "enable_$app";
        Modularity::updateAll([
            $field => 1
        ], [
            'id' => $id
        ]);

        $modules = $this->modularityService->getAllModules();
        if (isset($modules[$id]) && $modules[$id]['instance'] !== null) {
            $modules[$id]['instance']->active($app);
        }
        return $this->redirect([
            'index'
        ]);
    }

    public function actionDeactive($id, $app)
    {
        $field = "enable_$app";
        Modularity::updateAll([
            $field => 0
        ], [
            'id' => $id
        ]);

        $modules = $this->modularityService->getAllModules();
        if (isset($modules[$id]) && $modules[$id]['instance'] !== null) {
            $modules[$id]['instance']->deactive($app);
        }
        return $this->redirect([
            'index'
        ]);
    }
}